// 用来做接口封装的
import NProgress from "nprogress";
const base_url = "http://www.pudge.wang:3080/api";

const http = {
  get(url, params) {
    // params -> {a:3,b:4}
    if (params) {
      // 将{a:3,b:4} -> ?a=3&b=4
      const arr1 = Object.keys(params); // ["a", "b"]
      const arr2 = arr1.map((item) => {
        return item + "=" + params[item];
      }); // ["a=3", "b=4"]
      const str = arr2.join("&"); // a=3&b=4
      url += "?" + str;
    }

    return fetch(base_url + url)
      .then((response) => response.json())
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
  post(url, data) {
    NProgress.start();
    return fetch(base_url + url, {
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
      .then((response) => {
        NProgress.done();
        return response.json();
      })
      .then((res) => {
        if (res.status === 0) {
          return res;
        }
      });
  },
};

export default http;
